<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>动态数据绑定（二）</title>
</head>
<body>
 <script>
    var data = {
        name: 'xiaoming',
        age: '18',
        city: 'beijing'
    }; 
    function Observer(data) {
        this.data = data;
        this.walk(data);
        this.handlers = {};
    }
    Observer.prototype = {
        walk: function(obj) {
            var value,
                key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                    value = obj[key];
                    if (typeof value === 'object') {
                        new Observer(value);
                    }
                    this.convert(key, value); 
                }   
            }
        },
        convert: function(key, value) {
            var self = this;
            Object.defineProperty(this.data, key, {
                enumerable: true,
                configurable: true,
                get : function(){ 
                    console.log("你访问了" + key);
                    return value; 
                },
                set : function(newValue){
                    if (value == newValue) {
                        return;
                    }
                    console.log('你设置了' + key + '="' + newValue + '"');
                    value = newValue; 
                    if (typeof value === 'object') {
                        new Observer(value);
                    }
                    self.emit(key, value);
                }
            });
        },
        $watch: function(key, func) {
            var keys = this.handlers[key];
            if(keys){
                keys.push(func);
            } else {
                this.handlers[key] = [func];
            }
        },
        emit: function(key, value) {
            var keys = this.handlers[key];
            if (keys) {
                keys.forEach(function(item){
                    item(value);
                });
            }
        }
    }      
    var example = new Observer(data);
 </script>   
</body>
</html>